package com.dhruvtaara.beta.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.xml.sax.SAXException;

import com.dhruvtaara.beta.action.FileUploadAction;
import com.dhruvtaara.beta.toolset.AppLog;
import com.dhruvtaara.beta.toolset.DefaultEncryption;

public class FileUploaderServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * 
	 */
	private static final AppLog logger = new AppLog(
			DefaultEncryption.class.getName());

	/**
	 * 
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		ServletContext context = getServletContext();
		RequestDispatcher dispatcher = context
				.getRequestDispatcher("/view/admin/uploadQuestions.jsp");
		try {
			dispatcher.forward(request, response);
		} catch (ServletException e) {
			logger.Error(e.toString());
		} catch (IOException e) {
			logger.Error(e.toString());
		}
	}

	/**
	 * 
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		FileUploadAction action = new FileUploadAction();
		if (ServletFileUpload.isMultipartContent(request)) {
			ServletFileUpload uploader = new ServletFileUpload();
			uploader.setSizeMax(1048576);// 1MB
			try {
				FileItemIterator files = uploader.getItemIterator(request);
				try {
					if (action.doUpload(files)) {
						//success
					} else {
						response.getWriter()
								.write("Failed to upload file. Please ensure file has been selected.");
					}
				} catch (ParserConfigurationException e) {
					logger.Error(e.toString());
				} catch (SAXException e) {
					logger.Error(e.toString());
				}
			} catch (FileUploadException e) {
				logger.Error(e.toString());
			} catch (IOException e) {
				logger.Error(e.toString());
			}
		} else {
			try {
				response.getWriter()
						.write("Failed to upload file. Please ensure that form encoding is set to multipart");
			} catch (IOException e) {
				logger.Error(e.toString());
			}
		}
	}
}
